package rma.flp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;

/**
 * Uses the Google user service API to handle login and logout. 
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	UserService userService;
	
	@Autowired
	public LoginInterceptor(UserService userService) {
		this.userService = userService;
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		User user = userService.getCurrentUser();
		if (user == null) {
			String loginUrl = userService.createLoginURL(request.getRequestURI());
			response.sendRedirect(loginUrl);
			return false;
		} else {
			request.setAttribute("user", user);
			request.setAttribute("logoutUrl", userService.createLogoutURL("/"));
			return true;
		}
	}
	
}
